#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/8 17:05
# @Author  : jeff
# @FileName: redis_cache
import redis
from src.utils.read_config import redis_config
from src.utils.singleton import Singleton

host_name, port, password = redis_config()


class RedisCache(metaclass=Singleton):
    def __init__(self, host, port, db=0, password='', ttl=6000):
        super().__init__()
        self.redis = redis.Redis(host=host, port=port, db=db, password=password)
        self.ttl = ttl

    def update(self, k, v, ex=None):
        if ex is None:
            self.redis.set(name=k, value=v, ex=self.ttl)
        elif ex < 0:
            self.redis.set(name=k, value=v)
        else:
            self.redis.set(name=k, value=v, ex=ex)

    def get(self, k):
        v = self.redis.get(k)
        if v is None:
            return None
        else:
            v = v.decode('utf-8')
            return v

    def remove(self, k):
        self.redis.delete(k)

    def keys(self):
        keys = self.redis.keys()
        return [k.decode() for k in keys]

    def values(self):
        vs = self.redis.mget(self.keys())
        return [v.decode() if v else None for v in vs]


redis_cache = RedisCache(host=host_name, port=port, password=password, )
